<template>
	<view class="container">
		<view class="main" v-if="goods">
			<view class="nav">
				<view class="header">
					<view class="left overflow-hidden">
						<view class="d-flex align-items-center overflow-hidden store-selector" @tap="toStoreSelector">
							<image src="/static/images/order/location.png" style="width: 30rpx; height: 30rpx;" class="mr-10"></image>
							<view class="shop-info">
								<view class="shop-title">
									<text class="shop-name">{{ currentStore ? currentStore.name : '请选择门店' }}</text>
									<text class="shop-arrow">></text>
								</view>
								<text class="shop-address">{{ currentStore ? currentStore.address : '点击选择门店' }}</text>
							</view>
						</view>
					</view>
					<view class="right">
						<view class="switch-buttons">
							<view class="btn" :class="{ active: takeType != '外卖配送' }" @tap="takein">
								<text>到店</text>
							</view>
							<view class="btn" :class="{ active: takeType == '外卖配送' }" @tap="takeout">
								<text>配送</text>
							</view>
						</view>
					</view>
				</view>
				<view class="coupon">
					<text class="title">{{ appProperties.shopNotice }}</text>
				</view>
			</view>
			<view class="content">
				<!-- 左侧菜单栏 -->
				<scroll-view class="menus" :scroll-into-view="menuScrollIntoView" scroll-with-animation scroll-y>
					<view class="wrapper">
						<view
							v-for="(item, index) in goods"
							class="menu"
							:class="{ current: item.goodsCategoryName === currentCategoryName }"
							:id="`menu-${item.goodsCategoryName}`"
							:key="index"
							@tap="handleMenuTap(item.goodsCategoryName)"
						>
							<text>{{ item.goodsCategoryName }}</text>
							<view class="dot" v-show="menuCartNum(item.goodsCategoryName)">{{ menuCartNum(item.goodsCategoryName) }}</view>
						</view>
					</view>
				</scroll-view>

				<!-- 右侧商品列表 begin -->
				<scroll-view class="goods" scroll-with-animation scroll-y :scroll-top="categoryScrollTop" @scroll="handleGoodsScroll">
					<view class="wrapper">
						<view class="list">
							<!-- 商品分类展示 begin -->
							<view id="categoryParent" v-for="(category, index) in goods" :key="index">
								<view class="category" id="categoryMenu">
									<view>
										<text class="title">{{ category.goodsCategoryName }}</text>
									</view>
									<view class="items">
										<!-- 商品列表 begin -->
										<template v-if="category.goodsCategoryShow">
											<view class="good" v-for="(goods, key) in category.goodsList" :key="key">
												<!-- 推荐图标 -->
												<image v-if="highlightedGoods.includes(goods.name)" 
													  src="/static/images/ai-recommend-result.png"
													  class="recommend-icon">
												</image>
												<!-- <view class="collection-icon" @tap.stop="toggleCollection(goods)">
													<image 
														:src="isCollected(goods.id) ? '/static/images/star.png' : '/static/images/star-outline.png'"
														style="width: 40rpx; height: 40rpx;"
													/>
												</view> -->
												<image :src="formatImageUrl(goods.image)" class="image" @tap="showGoodDetailModal(goods)"></image>
												<view class="right">
													<text class="name">{{ goods.name }}</text>
													<text class="tips">{{ goods.description && goods.description != '' ? goods.description : goods.name }}</text>
													<view class="price_and_action">
														<text class="price">￥{{ goods.defaultPrice / 100 }}</text>
														<!-- 商品没有下架 -->
														<view v-if="goods.isSell">
															<!-- 要选商品规格详细信息 -->
															<view class="btn-group" v-if="goods.goodsPropertyVos && goods.goodsPropertyVos.length">
																<button type="primary" class="btn property_btn" hover-class="none" size="mini" @tap="showGoodDetailModal(goods)">
																	选规格
																</button>
																<view class="collection-btn" @tap.stop="toggleCollection(goods)">
																	<image 
																		:src="isCollected(goods.id) ? '/static/images/star.png' : '/static/images/star-outline.png'"
																		style="width: 40rpx; height: 40rpx;"
																	/>
																</view>
																<view class="dot" v-show="goodsCartNum(goods.id)">{{ goodsCartNum(goods.id) }}</view>
															</view>
															<!-- 可以直接添加，不用选择商品属性 -->
															<view class="btn-group" v-else>
																<button
																	type="default"
																	v-show="goodsCartNum(goods.id)"
																	plain
																	class="btn reduce_btn"
																	size="mini"
																	hover-class="none"
																	@tap="handleReduceFromCart(goods)"
																>
																	<view class="iconfont iconsami-select"></view>
																</button>
																<view class="number" v-show="goodsCartNum(goods.id)">{{ goodsCartNum(goods.id) }}</view>
																<button type="primary" class="btn add_btn" size="min" hover-class="none" @tap.stop="handleAddToCart(goods)">
																	<view class="iconfont iconadd-select"></view>
																</button>
																<view class="collection-btn" style="z-index: 99;" @click="toggleCollection(goods)">
																	<image 
																		:src="isCollected(goods.id) ? '/static/images/star.png' : '/static/images/star-outline.png'"
																		style="width: 40rpx; height: 40rpx;z-index: 99;"
																	/>
																</view>
															</view>
														</view>
														<!-- 已经下架了 -->
														<view v-else>
															<view class="btn-group">
																<button type="primary" disabled class="btn property_btn" style="text-decoration: line-through;" size="mini">
																	已售空
																</button>
																<view class="collection-btn" @tap.stop="toggleCollection(goods)">
																	<image 
																		:src="isCollected(goods.id) ? '/static/images/star.png' : '/static/images/star-outline.png'"
																		style="width: 40rpx; height: 40rpx;"
																	/>
																</view>
															</view>
														</view>
													</view>
												</view>
											</view>
										</template>
										<!-- 商品 end -->
									</view>
								</view>
							</view>
							<!-- 商品分类展示 end -->
						</view>
					</view>
				</scroll-view>
				<!-- 右侧商品列表 end -->
			</view>
			<!-- content end -->
			<!-- 购物车栏 begin -->
			<view class="cart-box" v-if="cart && cart.length">
				<view class="mark" @tap="cartPopupVisible = !cartPopupVisible">
					<image src="/static/images/menu/cart.png" class="cart-img"></image>
					<view class="tag">{{ getCartGoodsNumber }}</view>
				</view>
				<view class="price" @tap="cartPopupVisible = !cartPopupVisible">￥{{ getCartGoodsPrice / 100 }}</view>
				<view v-if="!appProperties.shopStatus"><button type="primary" class="pay-btn" disabled>商家休息中</button></view>
				<!-- <view v-else-if="new Date().getHours() >= appProperties.businessStartTime && new Date().getHours() < appProperties.businessEndTime"> -->
					<button type="primary" class="pay-btn" @tap="toPay()" :disabled="disabledPay">{{ disabledPay ? `差${spread / 100}元起送` : '去结算' }}</button>
				<!-- </view>
				<view v-else><button type="primary" class="pay-btn" disabled>未在营业时段</button></view> -->
			</view>
			<!-- 购物车栏 end -->
		</view>

		<!-- 商品详情模态框 begin -->
		<modal :show="goodDetailModalVisible" class="good-detail-modal" color="#5A5B5C" width="90%" custom padding="0rpx" radius="12rpx">
			<view class="cover">
				<image v-if="currentGoods.image" :src="formatImageUrl(currentGoods.image)" class="image"></image>
				<view class="btn-group">
					<image src="/static/images/menu/close.png" @tap="closeGoodDetailModal"></image>
				</view>
			</view>
			<scroll-view class="detail" scroll-y style="padding-bottom: 100px;">
				<view class="wrapper">
					<view class="basic">
						<view class="name">{{ currentGoods.name }}</view>
						<view class="tips">{{ currentGoods.description }}</view>
					</view>
					<!-- 商品的额外属性 -->
					<view class="properties" v-if="currentGoods.goodsPropertyVos && currentGoods.goodsPropertyVos.length">
						<view class="property" v-for="(goodsPropertyVo, index) in currentGoods.goodsPropertyVos" :key="index">
							<view class="title">
								<text class="name">
									<text v-if="goodsPropertyVo.required" style="color: red">*</text>
									{{ goodsPropertyVo.category }}
								</text>
							</view>
							<view class="values">
								<view
									class="value"
									v-for="(property, index2) in goodsPropertyVo.propertyList"
									:key="index2"
									:class="{ default: property.isDefault }"
									@tap="changePropertyDefault(index, index2)"
								>
									{{ property.propertyOption }}
									{{ property.rebasePrice ? '￥' + property.rebasePrice / 100 : property.extraPrice / 100 ? '￥' + property.extraPrice / 100 : '' }}
								</view>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
			<view class="action">
				<!-- 价格和属性 -->
				<view class="left">
					<view class="price">￥{{ currentGoods.realPrice / 100 }}</view>
					<view class="props" v-if="getGoodSelectedProps(currentGoods)">{{ getGoodSelectedProps(currentGoods) }}</view>
				</view>
				<!-- 模态窗里面增减商品 -->
				<view class="btn-group">
					<button type="default" plain class="btn" size="mini" hover-class="none" @tap="changeCurrentGoodsNumber(-1)">
						<view class="iconfont iconsami-select"></view>
					</button>
					<view class="number">{{ currentGoods.number }}</view>
					<button type="primary" class="btn" size="mini" hover-class="none" @tap="changeCurrentGoodsNumber(1)"><view class="iconfont iconadd-select"></view></button>
				</view>
			</view>
			<view class="add-to-cart-btn" @tap="addCurrentGoodsToCart()"><view>确认</view></view>
		</modal>
		<!-- 商品详情模态框 end -->

		<!-- 购物车详情popup -->
		<popup-layer direction="top" :show-pop="cartPopupVisible" class="cart-popup">
			<template slot="content">
				<view class="top"><text @tap="handleCartClear">清空</text></view>
				<scroll-view class="cart-list" scroll-y>
					<view class="wrapper">
						<view class="item" v-for="(goods, index) in cart" :key="index">
							<view class="left">
								<view class="name">{{ goods.name }}</view>
								<view class="props">{{ getGoodSelectedProps(goods) }}</view>
							</view>
							<view class="center">
								<text>￥{{ goods.realPrice / 100 }}</text>
							</view>
							<view class="right">
								<!-- 购物车里添加数量 -->
								<button type="default" plain size="mini" class="btn" hover-class="none" @tap="handleCartItemReduce(index)">
									<view class="iconfont iconsami-select"></view>
								</button>
								<view class="number">{{ goods.number }}</view>
								<!-- 购物车里减少数量 -->
								<button type="primary" class="btn" size="min" hover-class="none" @tap="handleCartItemAdd(index)">
									<view class="iconfont iconadd-select"></view>
								</button>
							</view>
						</view>
						<view class="item" v-if="takeType == '外卖配送'">
							<view class="left"><view class="name">包装费</view></view>
							<view class="center">
								<text>￥{{ appProperties.packingPrice / 100 }}</text>
							</view>
							<view class="left"><view class="name">配送费</view></view>
							<view class="center">
								<text>￥{{ appProperties.sendingPrice / 100 }}</text>
							</view>
						</view>
					</view>
				</scroll-view>
			</template>
		</popup-layer>
		<!-- 购物车详情popup -->

		<!-- 智能推荐按钮 -->
		<!-- <view class="ai-recommend-btn" @tap="toggleAIChat">
			<image src="/static/images/ai-recommend.png" mode="aspectFit"></image>
		</view> -->
		
		<!-- AI聊天弹窗 -->
		<!-- <view class="ai-chat-popup" :class="{ 'show': showAIChat }">
			<view class="chat-header">
				<text>智能推荐</text>
				<text class="close-btn" @tap="toggleAIChat">×</text>
			</view>
			
			<scroll-view class="chat-content" scroll-y scroll-with-animation 
						 :scroll-top="scrollTop">
				<view class="chat-messages">
					<view v-for="(msg, index) in chatMessages" 
						  :key="index" 
						  :class="['message', msg.type]">
						<text>{{msg.content}}</text>
					</view> -->
							<!-- 加载动画 -->
					<!-- <view v-if="isLoading" class="message ai loading">
						<view class="dot-loading">
							<view class="dot"></view>
							<view class="dot"></view>
							<view class="dot"></view>
						</view>
					</view>
				</view>
			</scroll-view>
			
			<view class="chat-input">
				<input type="text" 
					   v-model="userInput" 
					   placeholder="请输入您的问题"
					   :disabled="isLoading"
					   @confirm="sendMessage"/>
				<button @tap="sendMessage" 
						:disabled="isLoading || !userInput.trim()">
					发送
				</button>
			</view>
		</view> -->
	</view>
</template>

<script>
import modal from '@/components/modal/modal';
import popupLayer from '@/components/popup-layer/popup-layer';
import { mapState, mapMutations, mapActions, mapGetters } from 'vuex';
import staticGoods from '../../api/goods.js'


export default {
	components: {
		modal,
		popupLayer
	},
	data() {
		return {
			goods: null, // 引入静态数据
			currentCategoryName: '', // 默认分类
			categoryScrollTop: 0,
			menuScrollIntoView: '',
			goodDetailModalVisible: false, //是否饮品详情模态框
			currentGoods: {}, // 当前饮品
			selectedPropertyList: [], // 当前商品的属性
			cartPopupVisible: false,
			sizeCalcState: false,
			// 商品图片的基础路径
			goodsImageBaseUrl: this.$config.baseUrl + '/static/image/',
			collectedGoods: [], // 存储收藏的商品ID列表
			showAIChat: false,
			chatMessages: [],
			userInput: '',
			scrollTop: 0,
			highlightedGoods: [],
			isLoading: false,
			collectionList: [], // 收藏的商品ID列表
		};
	},

	onLoad() {
		if (!this.userInfo) {
			// 不登录 通过本地缓存直接进入
			let userInfo = uni.getStorageSync('userInfo');
			if (userInfo) {
				console.log('不登录，走本地缓存');
				this.$store.commit('login', userInfo);
			}
		}
		this.init();
		this.initStoreInfo(); // 初始化门店信息
	},
	computed: {
		...mapState({
			userInfo: state => state.userInfo,
			takeType: state => state.takeType,
			cart: state => state.cart,
			appProperties: state => state.appProperties,
			currentStore: state => state.currentStore
		}),
		...mapGetters([
			'getTakeType',
			'getCurrentStore'
		]),
		// 计算单个饮品添加到购物车的数量
		goodsCartNum() {
			return id =>
				this.cart.reduce((acc, cur) => {
					if (cur.id === id) {
						return (acc += cur.number);
					}
					return acc;
				}, 0);
		},
		// 计算该类商品的购买总数
		menuCartNum() {
			return goodsCategoryName =>
				this.cart.reduce((acc, cur) => {
					if (cur.goodsCategoryName === goodsCategoryName) {
						return (acc += cur.number);
					}
					return acc;
				}, 0);
		},
		// 计算购物车总数
		getCartGoodsNumber() {
			return this.cart.reduce((acc, cur) => acc + cur.number, 0);
		},
		// 计算购物车总价,
		getCartGoodsPrice() {
			let totalPrice = 0;
			this.cart.forEach(goods => {
				totalPrice += goods.realPrice * goods.number;
			});
			if (this.$store.getters.getTakeType == '外卖配送') {
				totalPrice += this.appProperties.packingPrice + this.appProperties.sendingPrice;
			}
			return totalPrice;
		}, // 是否达到起送价
		disabledPay() {
			return this.$store.getters.getTakeType == '外卖配送' && this.getCartGoodsPrice < this.appProperties.sendingNeedLeastPrice ? true : false;
		}, // 差多少元起送
		spread() {
			if (this.$store.getters.getTakeType != '外卖配送') return;
			return this.appProperties.sendingNeedLeastPrice - this.getCartGoodsPrice;
		},
		
	},
	onPullDownRefresh() {
		setTimeout(() => {
			uni.stopPullDownRefresh();
		}, 300);
		this.init();
	},
	methods: {
		...mapMutations([
			'set_take_type',
			'setCurrentStore'
		]),
		...mapActions([
			'initStoreInfo'
		]),
		//页面初始化
		async init() {
			let that = this;
			that.$request('/config', 'get').then(result => {
				console.log('刷新配置信息:' + JSON.stringify(result.data));
				that.$store.commit('set_app_properties', result.data);
			});

			// 检查是否有选择门店
			if (!this.currentStore) {
				uni.showToast({
					title: '请先选择门店',
					icon: 'none',
					duration: 2000
				});
				setTimeout(() => {
					this.toStoreSelector();
				}, 2000);
				return;
			}

			console.log('当前选择的门店:', this.currentStore);
			
			// 确保门店ID是有效的数字类型
			let storeId = this.currentStore.id;
			if (!storeId) {
				console.error('门店ID无效:', this.currentStore);
				uni.showToast({
					title: '门店信息有误，请重新选择',
					icon: 'none',
					duration: 2000
				});
				setTimeout(() => {
					this.toStoreSelector();
				}, 2000);
				return;
			}
			
			// 强制转换为数字类型
			if (typeof storeId === 'string') {
				storeId = parseInt(storeId);
			}
			
			console.log('使用的门店ID:', storeId);
			
			// 使用新的接口路径，确保ID是数字
			that.$request('/goods/goodsMenu/store/' + storeId, 'get')
				.then(result => {
					console.log('获取商品列表成功:', result);
					that.goods = result.data;
					that.sizeCalcState = false;
					uni.stopPullDownRefresh();
				})
				.catch(err => {
					console.error('获取商品列表失败:', err);
					// 如果是后端返回400(参数错误)或404，可能是门店ID问题
					if (err.status === 400 || err.status === 404) {
						console.error('可能是门店ID无效，尝试使用查询参数方式');
						// 尝试使用查询参数方式
						that.$request('/goods/goodsMenu/list?storeId=' + storeId, 'get')
							.then(result => {
								console.log('使用查询参数方式获取商品列表成功:', result);
								that.goods = result.data;
								that.sizeCalcState = false;
								uni.stopPullDownRefresh();
							})
							.catch(fallbackErr => {
								console.error('两种方式都失败, 无法获取商品列表:', fallbackErr);
								uni.showToast({
									title: '获取商品列表失败，请重试',
									icon: 'none'
								});
							});
					} else {
						uni.showToast({
							title: '获取商品列表失败',
							icon: 'none'
						});
					}
					uni.stopPullDownRefresh();
				});
		},
		toLogin() {
			uni.navigateTo({ url: '/pages/login/login' });
		},
		// 跳转到门店选择页面
		toStoreSelector() {
			uni.navigateTo({ url: '/pages/store/store-selector' });
		},
		// 选择到店自取的方式下单
		takein() {
			this.$store.commit('set_take_type', '到店自取');
		},
		// 选择外卖配送的方式下单
		takeout() {
			this.$store.commit('set_take_type', '外卖配送');
			// 如果外卖配送但用户未登录，需要先登录
			if (!this.userInfo) {
				uni.navigateTo({ url: '/pages/login/login' });
			}
		},
		handleMenuTap(goodsCategoryName) {
			if (!this.sizeCalcState) {
				this.calcSize();
			}

			this.currentCategoryName = goodsCategoryName;
			this.$nextTick(() => (this.categoryScrollTop = this.goods.find(item => item.goodsCategoryName == goodsCategoryName).top));
		},
		handleGoodsScroll({ detail }) {
			// if (!this.sizeCalcState) {
			// 	this.calcSize();
			// }
			// const { scrollTop } = detail;
			// let tabs = this.goods.filter(item => item.top < scrollTop).reverse();
			// console.log(tabs)
			// if (tabs.length > 0) {
			// 	this.currentCategoryName = tabs[0].goodsCategoryName;
			// }
		},
		// 读取本地存储的推荐商品
		loadHighlightedGoods() {
			this.highlightedGoods = [];
			try {
				const highlightedGoods = uni.getStorageSync('highlightedGoods');
				if (highlightedGoods) {
					this.highlightedGoods = JSON.parse(highlightedGoods);
					console.log('加载推荐商品:', this.highlightedGoods);
				}
			} catch (error) {
				console.error('读取推荐商品失败:', error);
			}
		},
		

		// 辅助函数，滚动时判断事件用
		calcSize() {
			let that = this;
			// 这里是真的坑!!! 微信里没法绑定获取，暂时只能这样了
			let view = uni.createSelectorQuery().selectAll('#categoryMenu');
			view.fields(
				{
					size: true // 返回高和宽
				},
				data => {
					// eg: {width: 219, height: 760}
				}
			).exec(res => {
				// 回调信息
				let h = 10;
				let whArr = res[0];
				console.log('右边菜单商品的高宽为: ', JSON.stringify(whArr));
				let goodsMenus = that.goods;
				for (let i = 0; i < that.goods.length; i++) {
					goodsMenus[i].top = h;
					h += whArr[i].height;
					goodsMenus[i].bottom = h;
				}
				that.sizeCalcState = true;
			});

		},
		// 获取商品具体价格，如大杯商品，小杯商品价格不同
		getGoodsRealPrice(goods) {
			console.log(goods);
			let realPrice = goods.realPrice;
			if (goods.goodsPropertyVos && goods.goodsPropertyVos.length) {
				let vos = goods.goodsPropertyVos;
				for (let i = 0; i < vos.length; i++) {
					let propertyList = vos[i].propertyList;
					for (let j = 0; j < propertyList.length; j++) {
						if (propertyList[j].isDefault && propertyList[j].realPrice) {
							realPrice = propertyList[j].realPrice;
							break;
						}
					}
				}
			}
			return realPrice;
		},
		// 显示当前商品的详情信息
		showGoodDetailModal(currentGoods) {
			currentGoods.number = 1;
			currentGoods.realPrice = this.getGoodsRealPrice(currentGoods);
			currentGoods.propertyStr = this.getGoodSelectedProps(currentGoods);
			this.currentGoods = JSON.parse(JSON.stringify(currentGoods)); // 深拷贝

			this.goodDetailModalVisible = true;
			this.selectedPropertyList = [];
			console.log('显示当前商品的详情信息', this.currentGoods);
		},
		closeGoodDetailModal() {
			// 关闭饮品详情模态框
			this.goodDetailModalVisible = false;
		},
		// 改变商品的某个默认属性值 要区分必选和多选的属性
		changePropertyDefault(categoryIndex, propertyIndex) {
			let propertyCategory = this.currentGoods.goodsPropertyVos[categoryIndex].category;
			let propertyList = this.currentGoods.goodsPropertyVos[categoryIndex].propertyList;
			if (propertyCategory != '加料') {
				// 必须选一个
				propertyList.forEach(property => (property.isDefault = false)); // 重置所有默认选择状态重新选择
				propertyList[propertyIndex].isDefault = true;
				if (propertyCategory == '大小') {
					this.currentGoods.realPrice = this.currentGoods.realPrice - this.currentGoods.defaultPrice + propertyList[propertyIndex].rebasePrice;
					this.currentGoods.defaultPrice = propertyList[propertyIndex].rebasePrice;
					this.currentGoods.number = 1;
					this.currentGoods.propertyStr = this.getGoodSelectedProps(this.currentGoods);
				}
			} else {
				// 可选项  加料或减料
				if (propertyList[propertyIndex].isDefault) {
					this.currentGoods.realPrice -= propertyList[propertyIndex].extraPrice;
					propertyList[propertyIndex].isDefault = false;
				} else {
					this.currentGoods.realPrice += propertyList[propertyIndex].extraPrice;
					propertyList[propertyIndex].isDefault = true;
				}
			}
		},
		// 计算当前饮品所选属性，空格隔开
		getGoodSelectedProps(goods) {
			if (goods.goodsPropertyVos) {
				let propertyStr = '';
				goods.goodsPropertyVos.forEach(goodsPropertyVo => {
					goodsPropertyVo.propertyList.forEach(property => {
						if (property.isDefault) {
							propertyStr += property.propertyOption + ' ';
						}
					});
				});
				return propertyStr;
			}
			return '';
		},
		// 改变当前商品数量
		changeCurrentGoodsNumber(number) {
			this.currentGoods.number += number;
			if (this.currentGoods.number < 0) {
				this.currentGoods.number = 0;
			} else if (this.currentGoods.number >= 100) {
				this.currentGoods.number = 100;
			}
		},
		// 将当前商品加入到购物车
		addCurrentGoodsToCart() {
			if (this.currentGoods && this.currentGoods.number) {
				this.handleAddToCart(this.currentGoods);
			}
			this.closeGoodDetailModal();
		},
		// 减少购物车里的商品数量, goodsId和propertyStr去比较
		handleReduceFromCart(goods) {
			let propertyStr = this.getGoodSelectedProps(goods);
			let cart = this.cart;
			for (let i = cart.length - 1; i >= 0; i--) {
				if (cart[i].id == goods.id && cart[i].propertyStr == propertyStr) {
					if (cart[i].number <= 1) cart.splice(i, 1);
					else cart[i].number -= 1;
					return;
				}
			}
		},
		// 添加到购物车
		handleAddToCart(goods) {
			let propertyStr = this.getGoodSelectedProps(goods);
			goods.propertyStr = propertyStr;
			let cart = this.cart;
			for (let i = cart.length - 1; i >= 0; i--) {
				if (cart[i].id == goods.id && cart[i].propertyStr == propertyStr) {
					cart[i].number++;
					return;
				}
			}

			// 购物车里不存在
			if (!goods.number) goods.number = 1;
			this.cart.push(JSON.parse(JSON.stringify(goods)));
		},
		// 清空购物车
		handleCartClear() {
			let that = this;
			uni.showModal({
				title: '提示',
				content: '确定清空购物车么',
				success: ({ confirm }) => {
					if (confirm) {
						that.cartPopupVisible = false;
						that.$store.commit('set_cart', []);
					}
				}
			});
		},
		// 在购物车里操作商品数量
		handleCartItemAdd(index) {
			this.cart[index].number += 1;
		},
		handleCartItemReduce(index) {
			if (this.cart[index].number === 1) {
				this.cart.splice(index, 1);
			} else {
				this.cart[index].number -= 1;
			}
			if (!this.cart.length) {
				this.cartPopupVisible = false;
			}
		},
		toPay() {
			this.cartPopupVisible = false;
			
			// 检查门店选择
			if (!this.currentStore) {
				uni.showModal({
					content: '请先选择门店',
					confirmText: '去选择',
					success: e => {
						if (e.confirm) {
							this.toStoreSelector();
						}
					}
				});
				return;
			}
			
			// 如果是外卖配送，需要检查用户登录和地址信息
			if (this.takeType == '外卖配送') {
				if (!this.userInfo) {
					uni.navigateTo({ url: '/pages/login/login' });
					return;
				}
				
				if (!this.userInfo.address || this.userInfo.address == '' || !this.userInfo.phone || this.userInfo.phone == '') {
					uni.showModal({
						content: '请先去设置收货信息',
						confirmText: '去设置',
						success: e => {
							if (e.confirm) {
								uni.navigateTo({ url: '/pages/mine/userinfo' });
							}
						}
					});
					return;
				}
			}

			console.log('进入支付页面');
			uni.navigateTo({
				url: '/pages/pay/pay'
			});
		},
		// 获取用户收藏列表
		async getCollectionList() {
			if (!this.userInfo) return;
			try {
				console.log('开始获取收藏列表, wxOpenid:', this.userInfo.wxOpenid);
				
				const result = await this.$request('/api/collection/ids', 'get', {
					wxOpenid: this.userInfo.wxOpenid
				});
				
				console.log('收藏列表API响应:', result);
				
				if (result && result.data) {
					this.collectionList = result.data;
					console.log('收藏列表获取成功:', this.collectionList);
				} else {
					// 如果没有数据或获取失败，确保列表为空数组
					this.collectionList = [];
					console.warn('收藏列表为空或获取数据格式不正确');
				}
			} catch (error) {
				console.error('获取收藏列表失败:', error);
				// 确保在失败时列表为空数组
				this.collectionList = [];
				
				// 在开发环境下，隐藏错误提示，因为这是正常的首次使用场景
				if (this.$config.debug) {
					console.log('开发环境中，首次使用收藏功能正常会返回404，直到创建第一个收藏');
				}
			}
		},
		// 判断商品是否被收藏
		isCollected(goodsId) {
			if (!this.userInfo || !this.collectionList) return false;
			return this.collectionList.includes(goodsId);
		},
		// 切换收藏状态
		async toggleCollection(goods) {
			if (!this.userInfo) {
				uni.showModal({
					title: '提示',
					content: '请先登录',
					success: (res) => {
						if (res.confirm) {
							uni.navigateTo({
								url: '/pages/login/login'
							});
						}
					}
				});
				return;
			}
			
			try {
				if (this.isCollected(goods.id)) {
					// 取消收藏
					await this.$request('/api/collection/remove', 'delete', {
						wxOpenid: this.userInfo.wxOpenid,
						goodsId: goods.id
					});
					// 更新本地收藏列表
					await this.getCollectionList();
					uni.showToast({
						title: '取消收藏成功',
						icon: 'success'
					});
				} else {
					// 添加收藏
					await this.$request('/api/collection/add', 'post', {
						wxOpenid: this.userInfo.wxOpenid,
						goodsId: goods.id
					});
					// 更新本地收藏列表
					await this.getCollectionList();
					uni.showToast({
						title: '收藏成功',
						icon: 'success'
					});
				}
			} catch (err) {
				console.error('收藏操作失败:', err);
				uni.showToast({
					title: err.message || '操作失败',
					icon: 'none'
				});
			}
		},
		
	
	
		formatImageUrl(imagePath) {
			if (!imagePath) return '';
			// For absolute URLs that already have http/https, return as is
			if (imagePath.startsWith('http')) return imagePath;
			// For relative paths, ensure they're properly formatted for Mini Program
			return this.goodsImageBaseUrl + imagePath;
		}
	},
	onShow() {
		// 检查是否有"门店刚刚更新"的标记
		const storeJustUpdated = uni.getStorageSync('storeJustUpdated');
		if (storeJustUpdated === 'true') {
			// 清除标记
			uni.removeStorageSync('storeJustUpdated');
			console.log('检测到门店刚刚更新，强制刷新数据');
			
			// 初始化门店信息并刷新数据
			this.initStoreInfo();
			setTimeout(() => {
				this.init(); // 强制重新加载数据
			}, 100); // 稍微延迟，确保门店信息已同步到Vuex
			
			return; // 直接返回，避免下面的检查
		}
		
		// 检查当前门店是否发生变化
		const storeInfo = uni.getStorageSync('currentStore');
		if (storeInfo) {
			try {
				let storedStore = JSON.parse(storeInfo);
				
				// 确保ID是数字类型
				if (storedStore && storedStore.id && typeof storedStore.id === 'string') {
					storedStore.id = parseInt(storedStore.id);
					// 重新保存修正后的数据
					uni.setStorageSync("currentStore", JSON.stringify(storedStore));
				}
				
				// 如果存储的门店与当前状态中的门店不同，重新加载数据
				if (!this.currentStore || storedStore.id !== this.currentStore.id) {
					console.log('门店已变更，重新加载数据');
					this.initStoreInfo(); // 更新当前门店信息
					this.init(); // 重新加载商品数据
				} else {
					// 确保即使门店相同，也检查是否有商品数据
					if (!this.goods) {
						console.log('商品数据为空，重新加载数据');
						this.init();
					}
				}
			} catch (e) {
				console.error('解析门店信息失败', e);
				// 如果解析失败，可能需要重新选择门店
				if (!this.currentStore) {
					console.log('无法解析门店信息且当前无选中门店，引导用户选择');
					setTimeout(() => {
						this.toStoreSelector();
					}, 1000);
				}
			}
		} else if (!this.currentStore) {
			// 如果没有本地存储的门店且当前也没有选中门店
			console.log('未找到门店信息，引导选择门店');
			setTimeout(() => {
				this.toStoreSelector();
			}, 1000);
		}
		
		// 原有的逻辑保持不变
		if (this.userInfo) {
			this.getCollectionList();
		}
		this.loadHighlightedGoods();
	}
};
</script>

<style lang="scss" scoped>
@import '~@/pages/menu/menu.scss';
.collection-icon {
	position: absolute;
	top: 10rpx;
	right: 10rpx;
	z-index: 1;
}
.header-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}
.ai-recommend-btn {
	position: fixed;
	right: 30rpx;
	top: 50%;
	transform: translateY(-50%);
	width: 100rpx;
	height: 100rpx;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 4rpx 16rpx rgba(0,0,0,0.2);
	z-index: 100;
	transition: all 0.3s ease;
	
	image {
		width: 60rpx;
		height: 60rpx;
	}
	
	&:active {
		transform: translateY(-50%) scale(0.95);
	}
}



@keyframes dotBounce {
	0%, 80%, 100% { 
		transform: scale(0);
	}
	40% { 
		transform: scale(1);
	}
}

// 高亮推荐商品的样式
.good {
	position: relative;
	
	.recommend-icon {
		position: absolute;
		top: 10rpx;
		right: 30rpx; // 放在收藏图标左边
		width: 50rpx;
		height: 50rpx;
		z-index: 2;
	}
}

.header {
	padding: 24rpx 30rpx;
	background-color: #fff;
	border-bottom: 1rpx solid #f5f5f5;
	display: flex;
	justify-content: space-between;
	align-items: flex-start;

	.left {
		flex: 1;
		padding-right: 20rpx;

		.shop-info {
			.shop-title {
				display: flex;
				align-items: center;
				margin-bottom: 4rpx;

				.shop-name {
					font-size: 34rpx;
					font-weight: 500;
					color: #333;
				}

				.shop-arrow {
					font-size: 28rpx;
					color: #999;
					margin: 0 6rpx;
				}
			}

			.shop-address {
				font-size: 20rpx;
				color: #666;
				display: block;
			}
		}
	}

	.right {
		.switch-buttons {
			display: flex;
			align-items: center;
			background: #F7F7F7;
			border-radius: 32rpx;
			padding: 4rpx;
			height: 64rpx;

			.btn {
				height: 56rpx;
				min-width: 96rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				border-radius: 28rpx;
				transition: all 0.2s ease;
				
				text {
					font-size: 28rpx;
					color: #999;
					line-height: 1;
				}

				&.active {
					background: #95C752;
					
					text {
						color: #fff;
					}
				}
			}
		}
	}
}

.store-selector {
	cursor: pointer;
	
	.shop-title {
		display: flex;
		align-items: center;
		
		.shop-name {
			font-weight: bold;
			max-width: 300rpx;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
		}
		
		.shop-arrow {
			margin-left: 10rpx;
			font-size: 24rpx;
			color: #999;
		}
	}
	
	.shop-address {
		font-size: 24rpx;
		color: #999;
		max-width: 400rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
}
</style>
